package com.byx.chatclient.view.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.byx.chatclient.R;
import com.byx.chatclient.adapter.SearchGroupAdapter;
import com.byx.chatclient.adapter.SearchUserAdapter;
import com.byx.chatclient.bean.SearchGroupBean;
import com.byx.chatclient.bean.SearchUserBean;
import com.byx.chatclient.entity.Constant;
import com.byx.chatclient.entity.Result;
import com.byx.chatclient.entity.ResultCode;
import com.byx.chatclient.entity.User;
import com.byx.chatclient.factory.RetrofitFactory;
import com.byx.chatclient.http.ActionRequest;
import com.byx.chatclient.utils.GradientStatusBarUtil;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * @author Superb
 */
@SuppressLint("NonConstantResourceId")
public class SearchMoreActivity extends AppCompatActivity {
    private static final int SEARCH_USER = 1;
    private static final int SEARCH_GROUP = 2;


    @BindView(R.id.iv_back)
    protected ImageView mIvBack;
    @BindView(R.id.et_search_more)
    protected EditText mEtSearchMore;
    @BindView(R.id.tv_search_more)
    protected TextView mTvSearchMore;
    @BindView(R.id.tv_search_type)
    protected TextView mTvSearchType;
    @BindView(R.id.rv_search_more_list)
    protected RecyclerView mRvSearchMoreList;
    @BindView(R.id.ll_search_more_result)
    protected LinearLayout mLlSearchMoreResult;
    @BindView(R.id.tv_search_more_failed)
    protected TextView mTvSearchMoreFailed;

    private SearchUserAdapter mUserAdapter;
    private SearchGroupAdapter mGroupAdapter;

    private int type;
    private Unbinder mUnbinder;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_more);
        GradientStatusBarUtil.getInstance().bind(this).withBackgroundResource(R.drawable.toolbar).init();
        mUnbinder = ButterKnife.bind(this);
        init();
        initListener();
    }

    private void initListener() {
        mEtSearchMore.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                mTvSearchMore.setVisibility(s.length() > 0 ? View.VISIBLE : View.GONE);
            }
        });
    }

    private void init() {
        Intent intent = getIntent();
        if (intent.hasExtra(SearchActivity.USER_EXTRA_KEY)) {
            type = SEARCH_USER;
            mTvSearchType.setText("查找人");
            initUserAdapter();
            String key = intent.getStringExtra(SearchActivity.USER_EXTRA_KEY);
            searchUser(key);
        }else if (intent.hasExtra(SearchActivity.GROUP_EXTRA_KEY)){
            type = SEARCH_GROUP;
            mTvSearchType.setText("查找群");
            initGroupAdapter();
            String key = intent.getStringExtra(SearchActivity.GROUP_EXTRA_KEY);
            searchGroup(key);
        }
        mRvSearchMoreList.setLayoutManager(new LinearLayoutManager(this));
    }

    private void initUserAdapter() {
        mUserAdapter = new SearchUserAdapter();
        mRvSearchMoreList.setAdapter(mUserAdapter);
        /*
         * 点击添加好友按钮
         */
        mUserAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            if (view.getId() == R.id.btn_add_friend){
                SearchUserBean userBean = mUserAdapter.getItem(position);
                Intent intent = new Intent(SearchMoreActivity.this, AddFriendActivity.class);
                intent.putExtra(Constant.INTENT_KEY_USER_BEAN,userBean);
                startActivity(intent);
            }
        });

        mUserAdapter.setOnItemClickListener((adapter, view, position) -> {
            //点击跳转到用户详情
            String loginId = mUserAdapter.getItem(position).getLoginId();
            User user = new User();
            user.setLoginId(loginId);
            Intent intent = new Intent(SearchMoreActivity.this,PersonDetailsActivity.class);
            intent.putExtra(Constant.PERSON_ID,user);
            startActivity(intent);
        });
    }

    private void initGroupAdapter() {
        mGroupAdapter = new SearchGroupAdapter();
        mRvSearchMoreList.setAdapter(mGroupAdapter);
        /*
          点击发送加群请求
         */
        mGroupAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            if (view.getId() == R.id.btn_add_group){
                Long groupId = mGroupAdapter.getItem(position).getGroupId();
//                    addGroup(groupId);
            }
        });
        /*
          点击查看群详情
         */
        mGroupAdapter.setOnItemClickListener((adapter, view, position) -> {
            // 传群id，跳转后访问接口，获取群聊信息，以及自己是否在群聊内
            Long groupId = mGroupAdapter.getItem(position).getGroupId();
            Intent intent = new Intent(SearchMoreActivity.this,GroupDetailActivity.class);
            intent.putExtra(Constant.GROUP_ID,groupId);
            startActivity(intent);
        });
    }

    private void searchUser(String searchKey){
        RetrofitFactory.getBean(ActionRequest.class).fuzzySearchUser(searchKey)
                .enqueue(new Callback<Result<List<SearchUserBean>>>() {
                    @Override
                    public void onResponse(@NonNull Call<Result<List<SearchUserBean>>> call, @NonNull Response<Result<List<SearchUserBean>>> response) {
                        if (response.isSuccessful()){
                            Result<List<SearchUserBean>> result = response.body();
                            if (result != null && result.getCode().equals(ResultCode.SUCCESS.code())){
                                List<SearchUserBean> userBeans = result.getData();
                                if (userBeans == null || userBeans.isEmpty()){
                                    mLlSearchMoreResult.setVisibility(View.GONE);
                                    mTvSearchMoreFailed.setVisibility(View.VISIBLE);
                                }else {
                                    mUserAdapter.setList(userBeans);
                                    mLlSearchMoreResult.setVisibility(View.VISIBLE);
                                    mTvSearchMoreFailed.setVisibility(View.GONE);
                                }
                            }
                        }
                    }

                    @Override
                    public void onFailure(@NonNull Call<Result<List<SearchUserBean>>> call, @NonNull Throwable t) {
                        t.printStackTrace();
                    }
                });
    }

    private void searchGroup(String searchKey){
        RetrofitFactory.getBean(ActionRequest.class).fuzzySearchGroup(searchKey)
                .enqueue(new Callback<Result<List<SearchGroupBean>>>() {
                    @Override
                    public void onResponse(@NonNull Call<Result<List<SearchGroupBean>>> call, @NonNull Response<Result<List<SearchGroupBean>>> response) {
                        if (response.isSuccessful()){
                            Result<List<SearchGroupBean>> result = response.body();
                            if (result != null && result.getCode().equals(ResultCode.SUCCESS.code())){
                                List<SearchGroupBean> groupBeans = result.getData();
                                if (groupBeans == null || groupBeans.isEmpty()){
                                    mLlSearchMoreResult.setVisibility(View.GONE);
                                    mTvSearchMoreFailed.setVisibility(View.VISIBLE);
                                }else {
                                    mGroupAdapter.setList(groupBeans);
                                    mLlSearchMoreResult.setVisibility(View.VISIBLE);
                                    mTvSearchMoreFailed.setVisibility(View.GONE);
                                }
                            }
                        }
                    }

                    @Override
                    public void onFailure(@NonNull Call<Result<List<SearchGroupBean>>> call, @NonNull Throwable t) {
                        t.printStackTrace();
                    }
                });
    }

    @OnClick({R.id.iv_back,R.id.tv_search_more,R.id.et_search_more})
    protected void onClick(View view){
        switch (view.getId()){
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_search_more:
                mTvSearchMore.setVisibility(View.GONE);
                mEtSearchMore.clearFocus();
                String searchKey = mEtSearchMore.getText().toString();
                if (type == SEARCH_USER){
                    searchUser(searchKey);
                }else {
                    searchGroup(searchKey);
                }
                break;
            case R.id.et_search_more:
                mLlSearchMoreResult.setVisibility(View.GONE);
                mTvSearchMoreFailed.setVisibility(View.GONE);
                mTvSearchMore.setVisibility(View.VISIBLE);
            default:break;
        }
    }

    @Override
    protected void onDestroy() {
        mUnbinder.unbind();
        GradientStatusBarUtil.getInstance().unbind();
        super.onDestroy();
    }
}